import { MetadataRoute } from "next";
import { webAPI } from "@/lib/api";
import type { Article, Case, Product } from "@/lib/api";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const baseUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://www.aiproducthome.com";

  // 静态页面
  const staticPages = [
    {
      url: baseUrl,
      lastModified: new Date(),
      changeFrequency: "daily" as const,
      priority: 1,
    },
    {
      url: `${baseUrl}/discover`,
      lastModified: new Date(),
      changeFrequency: "daily" as const,
      priority: 0.9,
    },
    {
      url: `${baseUrl}/cases`,
      lastModified: new Date(),
      changeFrequency: "daily" as const,
      priority: 0.9,
    },
    {
      url: `${baseUrl}/products`,
      lastModified: new Date(),
      changeFrequency: "weekly" as const,
      priority: 0.8,
    },
  ];

  // 动态获取文章页面
  let articlePages: MetadataRoute.Sitemap = [];
  try {
    const articlesRes = await webAPI.getArticles({ limit: 100, status: true });
    if (articlesRes.success) {
      articlePages = articlesRes.data.articles.map((article: Article) => ({
        url: `${baseUrl}/discover/detail/${article.slug}`,
        lastModified: new Date(article.updatedAt || article.publishedAt || article.createdAt),
        changeFrequency: "weekly" as const,
        priority: 0.7,
      }));
    }
  } catch (error) {
    console.error("获取文章sitemap失败:", error);
  }

  // 动态获取攻略页面
  let casePages: MetadataRoute.Sitemap = [];
  try {
    const casesRes = await webAPI.getCases({ limit: 100 });
    if (casesRes.success) {
      casePages = casesRes.data.cases.map((caseItem: Case) => ({
        url: `${baseUrl}/cases/detail/${caseItem.slug}`,
        lastModified: new Date(caseItem.updatedAt || caseItem.publishedAt || caseItem.createdAt),
        changeFrequency: "weekly" as const,
        priority: 0.7,
      }));
    }
  } catch (error) {
    console.error("获取攻略sitemap失败:", error);
  }

  // 动态获取产品页面
  let productPages: MetadataRoute.Sitemap = [];
  try {
    const productsRes = await webAPI.getProducts({ pageSize: 100 });
    if (productsRes.success) {
      productPages = productsRes.data.products.map((product: Product) => ({
        url: `${baseUrl}/products/${product.slug}`,
        lastModified: new Date(product.updatedAt || product.createdAt),
        changeFrequency: "weekly" as const,
        priority: 0.7,
      }));
    }
  } catch (error) {
    console.error("获取产品sitemap失败:", error);
  }

  // 添加产品提交页面
  const submitProductPage = {
    url: `${baseUrl}/submit-product`,
    lastModified: new Date(),
    changeFrequency: "monthly" as const,
    priority: 0.6,
  };

  return [...staticPages, ...articlePages, ...casePages, ...productPages, submitProductPage];
}
